package com.leyou.items.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.leyou.api.R;
import com.leyou.common.vo.SkuVo;
import com.leyou.common.vo.SpuItemAttrGroupVo;
import com.leyou.common.vo.param;
import com.leyou.entity.SpecParamEntity;
import com.leyou.entity.SpuDetailEntity;
import com.leyou.entity.SpuEntity;
import com.leyou.entity.BrandEntity;
import com.leyou.items.feign.GoodsFeign;
import com.leyou.items.service.GoodsItemService;
import com.leyou.items.vo.GoodsItemVo;
import com.leyou.items.vo.SkuItemSaleAttrVo;
import com.leyou.items.vo.catelogVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class GoodsItemServiceImpl implements GoodsItemService {

    @Resource
    GoodsFeign goodsFeign;

    @Autowired
    ThreadPoolExecutor executor;

   // @Override
    public GoodsItemVo items2(Long id) {
        GoodsItemVo goods = new GoodsItemVo();
        // 1.获取商品的spu信息
        R info = goodsFeign.info(id);
        SpuEntity spu = JSON.parseObject(JSON.toJSONString(info.get("spu")), new TypeReference<SpuEntity>() {
        });
        goods.setSubTitle(spu.getSubTitle());
        goods.setTitle(spu.getTitle());
        // 2.获取分类并设置信息
        R category = goodsFeign.getCategoryAllNameByid(spu.getCid1(), spu.getCid2(), spu.getCid3());
        String cname = JSON.toJSONString(category.get("data"));
        String[] split = cname.split("/");
        List<catelogVo> catelogVos = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            catelogVo cate = new catelogVo();
            if(i == 0){
                cate.setCatelogId(spu.getCid1());
            }else if (i == 1){
                cate.setCatelogId(spu.getCid2());
            }else {
                cate.setCatelogId(spu.getCid3());
            }
            cate.setCatelogName(split[i]);
            catelogVos.add(cate);
        }
        goods.setCatelogs(catelogVos);
        // 2.1  获取品牌并设置信息
        BrandEntity  brandEntity = JSON.parseObject(JSON.toJSONString( goodsFeign.getBreadInfoById(spu.getBrandId()).get("brand")), new TypeReference<BrandEntity>() {
        });
        goods.setBreadId(brandEntity.getId());
        goods.setBreadName(brandEntity.getName());

        // 3.获取商品sku信息
        List<SkuVo> skus = JSON.parseObject(JSON.toJSONString(goodsFeign.getInfoBySpuId(id).get("data")), new TypeReference<List<SkuVo>>() {
        });
        goods.setSkuList(skus);
        // 4.根据spuid 获取商品详细信息
        SpuDetailEntity spuDetail = JSON.parseObject(JSON.toJSONString(goodsFeign.SpuDetailInfo(id).get("data")), new TypeReference<SpuDetailEntity>() {
        });
        BeanUtils.copyProperties(spuDetail,goods);
        // 5. 获取spu的规格参数信息  获取销售属性的规格参数
        // 5.1 获取spu的规格参数信息 k 为属性id   v为属性值
        Map<Long, String> genericSpecMap = JSON.parseObject(spuDetail.getGenericSpec(), new TypeReference<Map<Long, String>>() {});
        List<SpuItemAttrGroupVo> groupVos = JSON.parseObject(JSON.toJSONString(goodsFeign.getGroupAttrByCid(spu.getCid3()).get("data")), new TypeReference<List<SpuItemAttrGroupVo>>() {
        });
        groupVos.forEach(groupVo->{
            List<param> collect = groupVo.getParams().stream().filter(f -> {
                return genericSpecMap.get(f.getParamId()) != null;
            }).map(m -> {
                m.setParamValue(genericSpecMap.get(m.getParamId()));
                return m;
            }).collect(Collectors.toList());
            groupVo.setParams(collect);
        });
        goods.setGroupAttrs(groupVos);
        // 5.2 获取销售属性的规格参数
        Map<Long, String> specialSpecMap = JSON.parseObject(spuDetail.getSpecialSpec(), new TypeReference<Map<Long, String>>() {});

        List<SpecParamEntity> params = JSON.parseObject(JSON.toJSONString(goodsFeign.listByCid(spu.getCid3()).get("data")), new TypeReference<List<SpecParamEntity>>() {
        });
        List<SkuItemSaleAttrVo>  saleAttrVos = new ArrayList<>();
        params.forEach(param->{
            if(!StringUtils.isEmpty(specialSpecMap.get(param.getId()))){
                SkuItemSaleAttrVo saleAttrVo = new SkuItemSaleAttrVo();
                saleAttrVo.setParamId(param.getId());
                saleAttrVo.setParamName(param.getName());
                saleAttrVo.setParamValues(specialSpecMap.get(param.getId()));
                saleAttrVos.add(saleAttrVo);
            }
        });
        goods.setSaleAttr(saleAttrVos);
        return goods;
    }


    @Override
    public GoodsItemVo items(Long id) throws ExecutionException, InterruptedException {
        GoodsItemVo goods = new GoodsItemVo();


        CompletableFuture<SpuEntity> spufuture = CompletableFuture.supplyAsync(() -> {
            // 1.获取商品的spu信息
            R info = goodsFeign.info(id);
            SpuEntity spu = JSON.parseObject(JSON.toJSONString(info.get("spu")), new TypeReference<SpuEntity>() {
            });
            return spu;
        }, executor);

        // 在spufuture线程执行完之后执行
        CompletableFuture<Void> catefuture = spufuture.thenAcceptAsync((res) -> {
            goods.setSubTitle(res.getSubTitle());
            goods.setTitle(res.getTitle());
            // 2.获取分类并设置信息
            R category = goodsFeign.getCategoryAllNameByid(res.getCid1(), res.getCid2(), res.getCid3());
            String cname = JSON.toJSONString(category.get("data"));
            String[] split = cname.split("/");
            List<catelogVo> catelogVos = new ArrayList<>();
            for (int i = 0; i < split.length; i++) {
                catelogVo cate = new catelogVo();
                if (i == 0) {
                    cate.setCatelogId(res.getCid1());
                } else if (i == 1) {
                    cate.setCatelogId(res.getCid2());
                } else {
                    cate.setCatelogId(res.getCid3());
                }
                cate.setCatelogName(split[i]);
                catelogVos.add(cate);
            }
            goods.setCatelogs(catelogVos);
        }, executor);

        // 在spufuture线程执行完之后执行
        CompletableFuture<Void> brandfuture = spufuture.thenAcceptAsync((res) -> {
            // 2.1  获取品牌并设置信息
            BrandEntity brandEntity = JSON.parseObject(JSON.toJSONString(goodsFeign.getBreadInfoById(res.getBrandId()).get("brand")), new TypeReference<BrandEntity>() {
            });
            goods.setBreadId(brandEntity.getId());
            goods.setBreadName(brandEntity.getName());
        }, executor);

        /**
         * 异步查询
         */
        CompletableFuture<Void> skufuture = CompletableFuture.runAsync(() -> {
            // 3.获取商品sku信息
            List<SkuVo> skus = JSON.parseObject(JSON.toJSONString(goodsFeign.getInfoBySpuId(id).get("data")), new TypeReference<List<SkuVo>>() {
            });
            goods.setSkuList(skus);
        }, executor);

        CompletableFuture<SpuDetailEntity> spuDetailfuture = CompletableFuture.supplyAsync(() -> {
            // 4.根据spuid 获取商品详细信息
            SpuDetailEntity spuDetail = JSON.parseObject(JSON.toJSONString(goodsFeign.SpuDetailInfo(id).get("data")), new TypeReference<SpuDetailEntity>() {
            });
            BeanUtils.copyProperties(spuDetail, goods);
            return spuDetail;
        }, executor);

        CompletableFuture<Void> Groupfuture = spufuture.thenAcceptAsync((spu) -> {
            spuDetailfuture.thenAcceptAsync((res) -> {
                // 5. 获取spu的规格参数信息  获取销售属性的规格参数
                // 5.1 获取spu的规格参数信息 k 为属性id   v为属性值
                Map<Long, String> genericSpecMap = JSON.parseObject(res.getGenericSpec(), new TypeReference<Map<Long, String>>() {
                });
                List<SpuItemAttrGroupVo> groupVos = JSON.parseObject(JSON.toJSONString(goodsFeign.getGroupAttrByCid(spu.getCid3()).get("data")), new TypeReference<List<SpuItemAttrGroupVo>>() {
                });
                groupVos.forEach(groupVo -> {
                    List<param> collect = groupVo.getParams().stream().filter(f -> {
                        return genericSpecMap.get(f.getParamId()) != null;
                    }).map(m -> {
                        m.setParamValue(genericSpecMap.get(m.getParamId()));
                        return m;
                    }).collect(Collectors.toList());
                    groupVo.setParams(collect);
                });
                goods.setGroupAttrs(groupVos);
            }, executor);
        }, executor);

        CompletableFuture<Void> Salefuture = spufuture.thenAcceptAsync((spu) -> {
            spuDetailfuture.thenAcceptAsync((res) -> {
                // 5.2 获取销售属性的规格参数
                Map<Long, String> specialSpecMap = JSON.parseObject(res.getSpecialSpec(), new TypeReference<Map<Long, String>>() {
                });
                List<SpecParamEntity> params = JSON.parseObject(JSON.toJSONString(goodsFeign.listByCid(spu.getCid3()).get("data")), new TypeReference<List<SpecParamEntity>>() {
                });
                List<SkuItemSaleAttrVo> saleAttrVos = new ArrayList<>();
                params.forEach(param -> {
                    if (!StringUtils.isEmpty(specialSpecMap.get(param.getId()))) {
                        SkuItemSaleAttrVo saleAttrVo = new SkuItemSaleAttrVo();
                        saleAttrVo.setParamId(param.getId());
                        saleAttrVo.setParamName(param.getName());
                        saleAttrVo.setParamValues(specialSpecMap.get(param.getId()));
                        saleAttrVos.add(saleAttrVo);
                    }
                });
                goods.setSaleAttr(saleAttrVos);
            }, executor);
        }, executor);

        //等待所有任务都完成
        CompletableFuture.allOf(catefuture,brandfuture,skufuture,Groupfuture,Salefuture).get();

        return goods;
    }
}
